package com.itheima.开启多线程.卖票.解决线程安全问题方案.同步方法;

/**
 * @Author 王加鑫
 * @Date 2021/5/22 14:56
 * @Version 1.0
 */
public class Ticket02 implements Runnable {
    //总共100张票
    private int ticket = 1000;


    @Override
    public void run() {
        while (true){
            boolean flag = method();
            if(flag){
                break;
            }
        }
    }

    /**
     * 同步方法
     * @return
     */
    public synchronized boolean method(){
        if(ticket <= 0){
            return true;
        }else {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ticket--;
            System.out.println(Thread.currentThread().getName() + "正在卖票,还剩下" + ticket + "张票");
            return false;
        }

    }
}
